package com.micangcaihang.micang.mvp.task.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;

import com.micangcaihang.common.base.fragment.BaseFragment;
import com.micangcaihang.common.utils.Properties;
import com.micangcaihang.common.utils.StringUtils;
import com.micangcaihang.common.utils.ToastUtils;
import com.micangcaihang.micang.R;
import com.micangcaihang.micang.databinding.FragmentTaskAssessResultBinding;
import com.micangcaihang.micang.entity.PickerEntity;
import com.micangcaihang.micang.entity.TaskAssessResultEntity;
import com.micangcaihang.micang.http.request.TaskAssessResultRequest;
import com.micangcaihang.micang.mvp.task.contract.TaskAssessResultContract;
import com.micangcaihang.micang.mvp.task.presenter.TaskAssessResultPresenter;
import com.micangcaihang.micang.view.PickerViewHelper;

import java.util.List;

import butterknife.OnTouch;

/**
 * <pre>
 *     author : Fandy
 *     e-mail : fandayongfly@gmail.com
 *     time   : 2017/07/24
 *     update : 2017/07/24
 *     desc   : 土地信息
 *     version: 1.0
 * </pre>
 */

public class TaskAssessResultFragment extends BaseFragment<TaskAssessResultPresenter, FragmentTaskAssessResultBinding> implements TaskAssessResultContract.View {
    private String id;
    private TaskAssessResultRequest mRequest;
    private TaskAssessResultRequest mOldRequest;
    private boolean isNetSuccess;
    private int pickerViewType;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getArguments().getString("id");
    }

    public static TaskAssessResultFragment newInstance(String id) {
        Bundle args = new Bundle();
        TaskAssessResultFragment fragment = new TaskAssessResultFragment();
        args.putString("id", id);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 获取资源文件布局
     *
     * @return 资源布局文件layout
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task_assess_result;
    }

    @Override
    public void initPresenter() {
        super.initPresenter();
        mPresenter.setId(id);
    }

    @Override
    protected void initData() {
        super.initData();
        mRequest = new TaskAssessResultRequest();
        mRequest.setId(id);
        mOldRequest = new TaskAssessResultRequest();
        mOldRequest.setId(id);
    }

    /**
     * 初始化按钮监听
     */
    @Override
    protected void initListener() {
        mViewBinding.setClickHandler(new ClickHandler());
    }

    @OnTouch({R.id.et_collateral_remark, R.id.et_collateral_opinion, R.id.et_special_note})
    boolean handleNoteFieldTouch(View v, MotionEvent event) {
        v.getParent().getParent().requestDisallowInterceptTouchEvent(true);
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                v.getParent().getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }
        return false;
    }

    /**
     * 返回土地信息信息
     *
     * @param entity
     */
    @Override
    public void returnAssessResultData(TaskAssessResultEntity entity) {
        isNetSuccess = true;
        if (StringUtils.isEmpty(entity.getCollateral_remark())) {
            entity.setCollateral_remark(_mActivity.getResources().getString(R.string.collateral_remark));
        }
        if (StringUtils.isEmpty(entity.getCollateral_opinion())) {
            entity.setCollateral_opinion(_mActivity.getResources().getString(R.string.collateral_opinion));
        }
        String[] excludsArray = new String[]{"choose_list", "id"};
        try {
            Properties.copyPropertiesExclude(entity, mRequest, excludsArray);
            Properties.copyPropertiesExclude(entity, mOldRequest, excludsArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //首家单价（元/㎡）
        if (!StringUtils.isEmpty(entity.getShoujia_unit_price())) {
            mViewBinding.etShoujiaUnitPrice.setText(entity.getShoujia_unit_price());
        }
        //首家总价（万元）
        if (!StringUtils.isEmpty(entity.getShoujia_total_price())) {
            mViewBinding.etShoujiaTotalPrice.setText(entity.getShoujia_total_price());
        }
        if (!StringUtils.isEmpty(entity.getRenda_unit_price())) {
            mViewBinding.etRendaUnitPrice.setText(entity.getRenda_unit_price());
        }
        if (!StringUtils.isEmpty(entity.getRenda_total_price())) {
            mViewBinding.etRendaTotalPrice.setText(entity.getRenda_total_price());
        }
        //评估单价（元/㎡）
        if (!StringUtils.isEmpty(entity.getAssessment_unit_price())) {
            mViewBinding.etAssessmentUnitPrice.setText(entity.getAssessment_unit_price());
        }
        //评估总价（万元）
        if (!StringUtils.isEmpty(entity.getAssessment_total_price())) {
            mViewBinding.etAssessmentTotalPrice.setText(entity.getAssessment_total_price());
        }
        //适用抵押率（%）
        if (!StringUtils.isEmpty(entity.getAssessment_mortgage_rate())) {
            mViewBinding.etAssessmentMortgageRate.setText(entity.getAssessment_mortgage_rate());
        }
        //贷款上限（万元）
        if (!StringUtils.isEmpty(entity.getAssessment_ceiling())) {
            mViewBinding.etAssessmentCeiling.setText(entity.getAssessment_ceiling());
        }
        //首家备注
        mViewBinding.tvShoujiaRemark.setText(entity.getChoose_list().getShoujia_remark_type());
        //仁达备注
        mViewBinding.tvRendaRemark.setText(entity.getChoose_list().getRenda_remark_type());
        //抵押物总体概述及备注
        mViewBinding.etCollateralRemark.setText(entity.getCollateral_remark());
        //抵押物调查评估意见
        mViewBinding.etCollateralOpinion.setText(entity.getCollateral_opinion());
        //特殊备注
        if (!StringUtils.isEmpty(entity.getSpecial_note())) {
            mViewBinding.etSpecialNote.setText(entity.getSpecial_note());
        }
    }

    @Override
    public void returnPickerData(List<PickerEntity> list, String title) {
        switch (pickerViewType) {
            case 1:
                PickerViewHelper.showOnePickerView(_mActivity, title, mRequest.getShoujia_remark_type(), list,
                        pickerEntity1 -> {
                            mRequest.setShoujia_remark_type(pickerEntity1.getSign_id());
                            mViewBinding.tvShoujiaRemark.setText(pickerEntity1.getTitle());
                        });
                break;
            case 2:
                PickerViewHelper.showOnePickerView(_mActivity, title, mRequest.getRenda_remark_type(), list,
                        pickerEntity1 -> {
                            mRequest.setRenda_remark_type(pickerEntity1.getSign_id());
                            mViewBinding.tvRendaRemark.setText(pickerEntity1.getTitle());
                        });
                break;
            default:
                break;
        }
    }

    public class ClickHandler {
        //首家备注
        public void onShowShoujiaRemarkPickerView(View view) {
            pickerViewType = 1;
            mPresenter.loadPickerViewData("remark_type", "首佳备注");
        }

        //仁达备注
        public void onShowRenDaRemarkPickerView(View view) {
            pickerViewType = 2;
            mPresenter.loadPickerViewData("remark_type", "仁达备注");
        }

        public void onSave(View view) {
            saveData();
        }
    }

    /**
     * 开始保存数据请求
     */
    public void saveData() {
        setSaveData();
        if (mRequest.toString().equals(mOldRequest.toString())) {
            ToastUtils.showLong("您没有更改任何信息，无需保存");
            return;
        }
        isNetSuccess = false;
        mPresenter.saveAssessResultData(mRequest);
    }

    /**
     * 判断是否保存过数据 没有的话点击保存去保存
     *
     * @return 是否保存当前页面数据
     */
    public boolean isSaveData() {
        //如果请求错误则返回true
        if (!isNetSuccess) {
            return true;
        }
        setSaveData();
        if (mRequest.toString().equals(mOldRequest.toString())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 设置请求数据
     */
    private void setSaveData() {
        mRequest.setShoujia_unit_price(mViewBinding.etShoujiaUnitPrice.getText().toString().trim());
        mRequest.setShoujia_total_price(mViewBinding.etShoujiaTotalPrice.getText().toString().trim());
        mRequest.setRenda_unit_price(mViewBinding.etRendaUnitPrice.getText().toString().trim());
        mRequest.setRenda_total_price(mViewBinding.etRendaTotalPrice.getText().toString().trim());
        mRequest.setAssessment_unit_price(mViewBinding.etAssessmentUnitPrice.getText().toString().trim());
        mRequest.setAssessment_total_price(mViewBinding.etAssessmentTotalPrice.getText().toString().trim());
        mRequest.setAssessment_mortgage_rate(mViewBinding.etAssessmentMortgageRate.getText().toString().trim());
        mRequest.setAssessment_ceiling(mViewBinding.etAssessmentCeiling.getText().toString().trim());
        mRequest.setCollateral_remark(mViewBinding.etCollateralRemark.getText().toString().trim());
        mRequest.setCollateral_opinion(mViewBinding.etCollateralOpinion.getText().toString().trim());
        mRequest.setSpecial_note(mViewBinding.etSpecialNote.getText().toString().trim());
    }
}
